package com.xz.supplierContract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.core.domain.model.LoginUser;
import com.xz.common.utils.DateUtils;
import com.xz.common.utils.SecurityUtils;
import com.xz.supplierContract.domain.SupplierContract;
import com.xz.supplierContract.domain.SupplierContractPriceScheme;
import com.xz.supplierContract.mapper.SupplierContractPriceSchemeMapper;
import com.xz.supplierContract.service.ISupplierContractPriceSchemeService;
import com.xz.supplierContract.vo.SupplierContractPriceSchemeVo;
import common.ECDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 合同价格方案Service业务层处理
 *
 * @author xz
 * @date 2024-02-26
 */
@Service
public class SupplierContractPriceSchemeServiceImpl extends ServiceImpl<SupplierContractPriceSchemeMapper, SupplierContractPriceScheme> implements ISupplierContractPriceSchemeService {
  @Autowired
  private SupplierContractPriceSchemeMapper supplierContractPriceSchemeMapper;

  /**
   * 查询合同价格方案
   *
   * @param id 合同价格方案主键
   * @return 合同价格方案
   */
  @Override
  public SupplierContractPriceScheme selectSupplierContractPriceSchemeById(Long id) {
    return supplierContractPriceSchemeMapper.selectSupplierContractPriceSchemeById(id);
  }

  /**
   * 估计合同ID查询合同价格方案
   * @param contractId
   * @return
   */
  @Override
  public List<SupplierContractPriceSchemeVo> selectByContractId(Long contractId) {
    return supplierContractPriceSchemeMapper.selectByContractId(contractId);
  }

  /**
   * 查询当下合同价格方案
   * @param supplierId
   * @return
   */
  @Override
  public  Map<Long,SupplierContractPriceSchemeVo> selectByCurrnet(Long supplierId) {
    //如果supplierId为null则直接返回
    Map<Long,SupplierContractPriceSchemeVo> map = new HashMap();
    if(null == supplierId){
      return map;
    }
    //如果supplierId不为null则开始获取数据库中，正在生效的价格方案
    SupplierContractPriceScheme scheme = new SupplierContractPriceScheme();
    scheme.setSupplierId(supplierId);
    try {
      scheme.setCurrentContractDate(ECDateUtils.getCurrentDate());
    } catch (ParseException e) {
      e.printStackTrace();
    }
    List<SupplierContractPriceSchemeVo> list = supplierContractPriceSchemeMapper.selectByCurrnet(scheme);
    // 转成以产品id为key，entity为value的map，然后返回。
    if(!CollectionUtils.isEmpty(list)){
      list.forEach(data->{ map.put(data.getProductId(),data); });
    }
    return map;
  }

  /**
   * 查询合同价格方案列表
   *
   * @param supplierContractPriceScheme 合同价格方案
   * @return 合同价格方案
   */
  @Override
  public List<SupplierContractPriceScheme> selectSupplierContractPriceSchemeList(SupplierContractPriceScheme supplierContractPriceScheme) {
    return supplierContractPriceSchemeMapper.selectSupplierContractPriceSchemeList(supplierContractPriceScheme);
  }

  /**
   * 更新合同附件
   *
   * @param supplierContract 合同
   * @param schemeList 合同价格方案集合
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void insertForContract(SupplierContract supplierContract, List<SupplierContractPriceScheme> schemeList) {
    if (!CollectionUtils.isEmpty(schemeList)) {
      LoginUser user = SecurityUtils.getLoginUser();
      schemeList.forEach(data -> {
        if(null != data.getProductId()){
          data.setContractId(supplierContract.getId());
          data.setContractNo(supplierContract.getContractNo());
          data.setSupplierId(supplierContract.getSupplierId());
          data.setCreateBy(user.getUserId());
          data.setCreateTime(DateUtils.getNowDate());
          data.setTenantId(user.getTenantId());
          data.setDeptId(user.getDeptId());
          supplierContractPriceSchemeMapper.insert(data);
        }
      });
    }
  }

  /**
   * 新增合同附件
   *
   * @param supplierContract 合同
   * @param schemeList 合同价格方案集合
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void updateForContract(SupplierContract supplierContract, List<SupplierContractPriceScheme> schemeList) {
    List<SupplierContractPriceScheme> addList = null;
    List<SupplierContractPriceScheme> updateList = null;
    if (!CollectionUtils.isEmpty(schemeList)) {
      addList = schemeList.stream().filter(a -> null == a.getId()).collect(Collectors.toList());
      updateList = schemeList.stream().filter(a -> null != a.getId()).collect(Collectors.toList());
    }

    //先删除id不再此次更新中的数据
    List<Long> updateId = updateList.stream().map(SupplierContractPriceScheme::getId).collect(Collectors.toList());
    supplierContractPriceSchemeMapper.delete(
      new LambdaQueryWrapper<SupplierContractPriceScheme>()
        .eq(SupplierContractPriceScheme::getContractId, supplierContract.getId())
        .notIn(!CollectionUtils.isEmpty(updateList), SupplierContractPriceScheme::getId, updateId)
    );

    if (!CollectionUtils.isEmpty(updateList)) {
      LoginUser user = SecurityUtils.getLoginUser();
      updateList.forEach(data -> {
        data.setUpdateBy(user.getUserId());
        data.setUpdateTime(DateUtils.getNowDate());
        supplierContractPriceSchemeMapper.updateSupplierContractPriceScheme(data);
      });
    }

    if (!CollectionUtils.isEmpty(addList)) {
      LoginUser user = SecurityUtils.getLoginUser();
      addList.forEach(data -> {
        if(null != data.getProductId()){
          data.setContractId(supplierContract.getId());
          data.setContractNo(supplierContract.getContractNo());
          data.setSupplierId(supplierContract.getSupplierId());
          data.setCreateBy(user.getUserId());
          data.setCreateTime(DateUtils.getNowDate());
          data.setTenantId(user.getTenantId());
          data.setDeptId(user.getDeptId());
          supplierContractPriceSchemeMapper.insert(data);
        }
      });
    }
  }


  /**
   * 批量删除合同价格方案
   *
   * @param ids 需要删除的合同价格方案主键
   * @return 结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int deleteSupplierContractPriceSchemeByIds(Long[] ids) {
    return supplierContractPriceSchemeMapper.deleteSupplierContractPriceSchemeByIds(ids);
  }

  /**
   * 删除合同价格方案信息
   *
   * @param id 合同价格方案主键
   * @return 结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int deleteSupplierContractPriceSchemeById(Long id) {
    return supplierContractPriceSchemeMapper.deleteSupplierContractPriceSchemeById(id);
  }
}
